package com.fkcai.hansoul.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 阿里云对象存储工具类
 */
@Component
public class OssUtil {
	private final OSS ossClient;
	private final String bucketName;
	private final String endpoint;
	
	// 提供构造器
	public OssUtil(OSS ossClient,
	               @Value("${aliyun.oss.bucket-name}") String bucketName,
	               @Value("${aliyun.oss.endpoint}") String endpoint) {
		this.ossClient = ossClient;
		this.bucketName = bucketName;
		this.endpoint = endpoint;
	}
	
	
	/**
	 * 将文件上传到 oss
	 * @param inputStream 文件
	 * @param objectName 存储路径
	 * @return 文件路径
	 */
	public String uploadFile(InputStream inputStream, String objectName) {
		ossClient.putObject(bucketName, objectName, inputStream);
		
		String fullPath = "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + objectName;
		
		return fullPath;
	}
	
	/**
	 * 删除文件
	 * @param objectName 文件路径
	 */
	public void deleteFile(String objectName) {
		ossClient.deleteObject(bucketName, objectName);
	}
	
}
